# -*- coding: utf-8 -*-
'''
Created on 2 sept. 2012

@author: Olivier
'''
import socket               # Import socket module
import pickle
from Data.Player import Player
import threading
from ClientTreatment import ClientTreatment
import time

 
class Client(threading.Thread):
    '''
    A class to connect a player to the server
    '''
    def __init__(self, inIp, inPort, inController):
        '''
        Constructor
        '''
        threading.Thread.__init__(self)
        
        self.__mIp   = inIp #ip of the server
        self.__mPort = inPort #port of the server
        self.__mClient = socket.socket()         # Create a socket object
        self.__mStopClient = False
        self.__mController = inController
        
    def SendInit(self):
        if self.__mClient is None: return
        thePlayer = Player('Sokaa') #Create a player
        self.Send(thePlayer) #send the player
        
        
    def run(self):
        '''
        function to use to start the client and get the data send by the server
        '''
        self.__mClient.connect((self.__mIp, self.__mPort))
        self.__mStopClient = False
        self.SendInit()
        
        while not self.__mStopClient:
            #try:
            theData = self.Received()
            
            if theData: # si on ne recoit plus rien
                ClientTreatment(theData, self)
            elif theData is None:
                break
            #except:
            #    print 'Error'
                
                
        self.__mClient.close()
        
    
    def Stop(self):
        '''
        function to stop the client and disconnect it from the server
        '''
        self.Send('Disconnect')
        self.__mStopClient = True
          
    def GetController(self):
        '''
        return the controller
        '''
        return self.__mController
        
    def Send(self, inObject):
        '''
        function to send a data or an object
        '''
        if self.__mClient is None: return
        if inObject is None: return
        self.__mClient.send(pickle.dumps(inObject))
        
    def Received(self):
        '''
        function to reveive a data and return it
        '''
        if self.__mClient is None: return
        theData = self.__mClient.recv(1024)
        if not theData: return None
        theObject = pickle.loads(theData)
        return theObject
        
     
if __name__ == "__main__":
    """
    Main for test the client
    """
    theClient = Client("localhost", 12345, None)
    theClient.start()
    time.sleep(2)
    theClient.Send('KIKOOOO1')
    time.sleep(2)
    theClient.Send('KIKOOOO2')
    time.sleep(2)
    theClient.Stop()
    
    